package com.incar.chuxing.payAndShare;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;

import com.alipay.sdk.app.AuthTask;
import com.incar.chuxing.bean.AliAuthEvent;
import com.incar.chuxing.bean.AuthResult;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

/**
 * Created by michaelpi on 2018/6/11.
 */

public class ZfbLoginUtil {

    private Activity activity;
    private static final int SDK_PAY_FLAG = 1;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("resultStatus", authResult.getResultStatus());
                jsonObject.put("result", authResult.getResult());
                jsonObject.put("memo", authResult.getMemo());
                EventBus.getDefault().post(new AliAuthEvent(jsonObject));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    public ZfbLoginUtil(Activity activity) {
        this.activity = activity;
    }

    public void zfbLogin(String infoStr) {
        Runnable authRunnable = () -> {
            // 构造AuthTask 对象
            AuthTask authTask = new AuthTask(activity);
            // 调用授权接口，获取授权结果
            Map<String, String> result = authTask.authV2(infoStr, true);

            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        };
        // 必须异步调用
        Thread authThread = new Thread(authRunnable);
        authThread.start();
    }
}
